/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rafkind.resrev.dao.impl;

import com.rafkind.resrev.dao.UserDao;
import com.rafkind.resrev.data.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.jasypt.util.password.BasicPasswordEncryptor;


/**
 *
 * @author dave
 */
public class UserDaoImpl implements UserDao {
  private EntityManager manager;
  
  public User authenticateUser(String loginName, String password) {        
    User user = getUser(loginName);
      
    if (user != null) {
      //System.out.println("Found user " + loginName + " with password " + password);
      BasicPasswordEncryptor bpe = new BasicPasswordEncryptor();
      if (bpe.checkPassword(password, user.getPassword())) {
        //System.out.println("Passwords matched!");
        return user;
      } else {
        //System.out.println("bad password");
      }
    }
    
    return null;
    
  }

  public User getUser(String loginName) {
    Query query = getEntityManager()
        .createQuery("select u from User u where u.loginName = :loginName");
    query.setParameter("loginName", loginName);
    //System.out.println("Looking for user " + loginName);
    try {
      User user = (User) query.getSingleResult();
      //System.out.println("Found user " + user);
      return user;
    } catch (NonUniqueResultException nurex) {
      //System.out.println("Too many users found!");
    } catch (NoResultException nrex) {       
      //System.out.println("No user found!");
    }
    return null;
  }
  
  public User getUser(int id) {
    return getEntityManager().find(User.class, id);
  }
  
  public int countAllUsers() {
    Query query = getEntityManager().
        createQuery("select COUNT(u) from User u");
    
    return ((Long) query.getSingleResult()).intValue();
  }
  
  public void saveUser(User u) {
    //System.out.println("Saving user " + u);
    
    if (u.getId() == null || u.getId() == 0)      
      getEntityManager().persist(u);
    else
      getEntityManager().merge(u);
  }
  
  public void ensureAdminUserExists() {
    User adminUser = getUser(User.DEFAULT_ADMIN_LOGIN_NAME);
    //System.out.println("No default admin user exists!");
    if (adminUser == null) {
      adminUser = User.createDefaultAdminUser();
      
      saveUser(adminUser);
      //System.out.println("Created a default admin user.");
    }
  }

  public List<User> getAllUsers() {
    Query query = getEntityManager()
        .createQuery("select u from User u");
    return query.getResultList();       
  }  
  
  public List<User> getAllUsers(int first, int count, 
      String orderByAttribute, boolean ascending) {
    
    Query query = getEntityManager()
        .createQuery("select u from User u order by u." + orderByAttribute 
          + (ascending ? " ASC" : " DESC"));
    query.setFirstResult(first);
    query.setMaxResults(count);
    
    return query.getResultList();
  }
  
  public void deleteUser(User user) {
    getEntityManager().remove(user);
  }
  
  protected EntityManager getEntityManager() {
    return manager;
  }

  @PersistenceContext
  public void setEntityManager(EntityManager em) {
    manager = em;
  }  
}